<?php


namespace App\Http\Controllers\App;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Repositories\Activity\Pet2022\PetRepository;
use App\Repositories\Lottery\SettingRepository;
use App\Repositories\Lottery\UserRepository;
use App\Repositories\UserDataRepository;
use App\Resource\User\BalanceResource;
use App\Response\Response;
use App\Services\Draw\DrawConst\CacheKey;
use App\Services\Draw\DrawManager;
use App\Services\Draw\Enum\DrawEnum;
use Illuminate\Http\Request;
use App\Resource\Setting\Resource as SettingResource;
use Illuminate\Support\Facades\DB;

class LotteryPetController extends BaseController
{
    protected $drawType = 'pet';

    public function balance(Request $request)
    {
        $userId  = (int)UID;
        $balance = UserRepository::getInstance()->info($userId);
        $model   = BalanceResource::make($balance);
        return Response::sendData($model);
    }

    public function levels(Request $request)
    {
        $levelList = (new DrawManager($this->drawType))->getLevelList();
        return Response::sendData($levelList);
    }


    public function user(Request $request)
    {
        $userId       = (int)UID;
        $userDrawInfo = (new DrawManager($this->drawType))->getUserDrawInfo($userId);
        return Response::sendData($userDrawInfo);
    }

    public function illustration(Request $request)
    {
        $poolConfig                       = (new DrawManager($this->drawType))->getPoolConfig();
        $illustration['help_info']        = $poolConfig['help_info'];
        $illustration['season_help_info'] = $poolConfig['season_help_info'] ?? '';
        return Response::sendData($illustration);
    }


    public function setting(Request $request)
    {
        $setting = SettingRepository::getInstance()->one([]);
        $model   = SettingResource::make($setting);
        return Response::sendData($model);
    }

    public function rank(Request $request)
    {
        $userId       = (int)UID;
        $type         = $request->input('type');
        $limit        = (int)$request->query('per_page', 10);
        $rankListData = (new DrawManager($this->drawType))->getRankList($userId, $type, $limit);

        $rankUserIds        = array_keys($rankListData['rank_list']);
        $rankUserIds[]      = $userId;
        $userInfoList       = app('repo_user_data')->batchGetUserInfoByIds($rankUserIds, ['user_id', 'user_code', 'nickname', 'head_picture']);
        $userInfoListWithId = $userInfoList->KeyBy('user_id');
        $rankRes            = [];

        $rankRes['user_rank'] = ['user_id' => $userId, 'user_code' => $userInfoListWithId[$userId]['user_code'], 'nickname' => $userInfoListWithId[$userId]['nickname'], 'head_picture' => $userInfoListWithId[$userId]['head_picture'], "diff" => null,
                                 'index'   => ($rankListData['user_rank']['rank'] !== null) ? ($rankListData['user_rank']['rank'] + 1) : 0, 'score' => $rankListData['user_rank']['score'] ?? 0];

        $index         = 1;
        $lastRankScore = 0;
        foreach ($rankListData['rank_list'] as $key => $rankScore) {
            $rankRes['rank_list'][] = ['user_id' => $key, 'user_code' => $userInfoListWithId[$userId]['user_code'], 'nickname' => $userInfoListWithId[$key]['nickname'], 'head_picture' => $userInfoListWithId[$key]['head_picture'],
                                       'index'   => $index, 'diff' => ($lastRankScore - $rankScore) < 0 ? 0 : ($lastRankScore - $rankScore), 'score' => $rankScore];

            if ($key == $userId) {
                $rankRes['user_rank']['diff']  = ($lastRankScore - $rankListData['user_rank']['score']) < 0 ? 0 : ($lastRankScore - $rankListData['user_rank']['score']);
                $rankRes['user_rank']['index'] = $index;
            }
            $lastRankScore = $rankScore;
            $index++;
        }
        if ($rankRes['user_rank']['diff'] === null) {
            $rankRes['user_rank']['diff'] = $lastRankScore - $rankListData['user_rank']['score'];
        }
        return Response::sendData($rankRes);
    }

    public function seasonRank(Request $request)
    {
        $type    = $request->input('type', 'current');
        $rankRes = [];
        //当前赛季
        $latestSeason = app('model_lottery_pet_season_statistics')->latestSeason();
        if (empty($latestSeason)) {
            return Response::sendData(['list' => [], 'season' => '']);
        }
        $rankRes = ['season' => "", 'list' => null];
        if ($type == 'last') {
            //上赛季
            $lastSeason = app('model_lottery_pet_season_statistics')->one([['season', '<', $latestSeason->season]]);
            if (empty($lastSeason)) {
                return Response::sendData($rankRes);
            }

            $rankRes['list']   = app('model_lottery_pet_user_season_record')->list(['season' => $lastSeason->season], ['user_id', 'prop_count'], 'prop_count');
            $rankRes['season'] = $lastSeason->season;

        } else {
            $rankRes['list']   = app('model_lottery_pet_user_season_record')->list(['season' => $latestSeason->season], ['user_id', 'prop_count'], 'prop_count');
            $rankRes['season'] = $latestSeason->season;
        }
        $userIds            = $rankRes['list']->pluck('user_id')->toArray();
        $userDataList       = app('repo_user_data')->batchGetUserInfoByIds($userIds, ['user_id', 'nickname', 'head_picture']);
        $userDataListWithId = $userDataList->KeyBy('user_id');
        foreach ($rankRes['list'] as $key => &$data) {
            $data['rank']         = $key + 1;
            $data['nickname']     = isset($userDataListWithId[$data['user_id']]) ? $userDataListWithId[$data['user_id']]['nickname'] : "";
            $data['head_picture'] = isset($userDataListWithId[$data['user_id']]) ? $userDataListWithId[$data['user_id']]['head_picture'] : "";
        }

        return Response::sendData($rankRes);
    }

    public function prizes(Request $request)
    {
        $prizeRes              = [];
        $drawManager           = (new DrawManager($this->drawType));
        $prizeList             = $drawManager->getAllPrizeList();
        $prizeRes['gift_list'] = $prizeList;
        //$prizeRes['exclusive_gift_list'] = $drawManager->getCriticalGiftList();
        $prizeRes['plutocrat_list']      = $drawManager->getAllPlutocratList();
        return Response::sendData($prizeRes);
    }

    public function swap(Request $request)
    {
        $appVersion = $request->header('appVersion');
        $clientType = $request->header('clientType');
        $this->checkVersion($clientType, $appVersion);

        $userId = (int)UID;
        $count  = intval($request->input('count'));
        if ($count <= 0) {
            throw new BasicException(-1, '非法请求');
        }
        (new DrawManager($this->drawType))->swapBalance($userId, $count);
        return Response::sendData([]);
    }

    public function draw(Request $request)
    {
        $appVersion = $request->header('appVersion');
        $clientType = $request->header('clientType');
        $this->checkVersion($clientType, $appVersion);

        $userId = (int)UID;
        $count  = (int)($request->input('count'));
        $config_count_arr =  explode(',',app('model_config')->getValue(strtoupper($this->drawType).'_DRAW_INFO') ?? '1,10,100');
        if ($count <= 0 || !in_array($count, $config_count_arr)) {
            throw new BasicException(-1, '非法请求');
        }
        $giftListRes = [];
        $totalCoin   = 0;
        $poolConfig  = app('model_lottery_pet_pool_config')->info();
        //查询用户赛季成绩
        $latestSeason = app('model_lottery_pet_season_statistics')->latestSeason();
        //查询用户的赛季道具数
        $userSeasonInfo = app('model_lottery_pet_user_season_record')->one(['season' => $latestSeason->season, 'user_id' => $userId]);
        if (empty($userSeasonInfo)) {
            $userSeasonInfo['prop_count'] = 0;
        }
        // $draw = LotteryRepository::getInstance()->draw($userId, $count);
        $drawData = (new DrawManager($this->drawType))->draw($userId, $count);

        $drawPropCount = 0;
        if (!empty($drawData['critical_gift'])) {

            $giftListRes[] = ['id'   => $drawData['critical_gift']['id'], 'name' => $drawData['critical_gift']['name'], 'picture' => $drawData['critical_gift']['picture'],
                              'type' => DrawEnum::PROP_GIFT_TYPE, 'critical_gift_level' => $drawData['critical_gift']['level'], 'count' => $drawData['critical_gift']['count'], 'price' => $drawData['critical_gift']['price']];
            //$totalCoin     += $drawData['critical_gift']['price'];
        }


        $data = $this->forDrawGift($drawData, $totalCoin);
        $totalCoin = $data['totalCoin'];
        $is_show_price = $data['is_show_price'];
        $is_show_animation = $data['is_show_animation'];
        $drawData = $data['drawData'];
        $giftListRes = array_merge($giftListRes, $drawData['gift_list']);
        $seasonValue = app('redis')->connection('game')->get("pet:seasonValue");

        $userSeasonInfo['prop_count'] += $drawData['critical_gift']['count'];
        if ($seasonValue + $drawPropCount > $poolConfig['lucky_count']) {
            $userSeasonInfo['prop_count'] = $userSeasonInfo['prop_count'] - ($seasonValue + $drawPropCount - $poolConfig['lucky_count']);
        }

        $rankMessage = "";
        if (!empty($latestSeason) && $drawPropCount > 0) {
            //考虑到大部分人是在排行榜外 优先只查第10名数据
            //查询第10名分数
            $rank10 = app('model_lottery_pet_user_season_record')->list(['season' => $latestSeason->season], ['user_id', 'prop_count'], 'prop_count', "desc", 1, 9);


            if (!empty($rank10[0]) && $userSeasonInfo['prop_count'] < $rank10[0]['prop_count']) {
                $rankMessage = "距离上榜获取额外奖励还差" . ($rank10[0]['prop_count'] - $userSeasonInfo['prop_count']);
            } else {
                $rankList = app('model_lottery_pet_user_season_record')->list(['season' => $latestSeason->season], ['user_id', 'prop_count'], 'prop_count', "desc", 10);

                foreach ($rankList as $key => $rankData) {
                    if ($rankData['prop_count'] <= $userSeasonInfo['prop_count']) {
                        if ($key == 0) {
                            $rankMessage = "当前赛季第1名，预计获得额外三倍";
                        } else {
                            $rankMessage = "当前赛季第" . ($key + 1) . "名，距离上一名还差" . ($rankList[$key - 1]['prop_count'] - $userSeasonInfo['prop_count']);
                        }
                        break;
                    }
                }
                if (empty($rankMessage)) {
                    if (!isset($key) || $key === null) {
                        $rankMessage = "当前赛季第1名，预计获得额外三倍";
                    } else {
                        $rankMessage = "当前赛季第" . ($key + 2) . "名，距离上一名还差" . ($rankList[$key]['prop_count'] - $userSeasonInfo['prop_count']);
                    }
                }
            }
        }

        /*try {
            PetRepository::getInstance()->addCouponCount($userId, $count);
        } catch (BasicException $e) {
            if ($e->getCode() != 600001) {
                throw $e;
            }
        }*/

        $drawRes = ["gift_list" => $giftListRes, 'total_coin' => $totalCoin, 'rank_message' => $rankMessage, 'is_show_price' => $is_show_price, 'is_show_animation' => $is_show_animation];
//        $draw = LotteryRebuildRepository::getInstance()->draw($userId, $count);
//        $models = DrawRecordRepository::getInstance()->get(['draw_id' => $draw->id])->sortByDesc('prize_price');
        return Response::sendData($drawRes);
    }

    public function getNotifyGiftList(Request $request)
    {
        $count          = (int)($request->input('count', 100));
        $notifyTextList = [];
        $notifyList     = (new DrawManager($this->drawType))->getNotifyGiftList($count);

        foreach ($notifyList as $notify) {
            $txt = "<font color='#3F3A75'>" . $notify['nickname'] . " </font>";
            $txt .= "<font color='#3F3A75'>获得了</font>";

            $txt              .= '<font color="#FF7200">价值' . $notify['gift_price'] . '</font>';
            $txt              .= '<font color="#FF7200">金币</font>';
            $txt              .= "<font color='#3F3A75'>的 </font>";
            $txt              .= '<font color="#BA59FF">' . $notify['gift_name'] . ' x ' . $notify['count'] . '</font>';
            $notifyTextList[] = $txt;
        }
        return Response::sendData($notifyTextList);
    }

    public function clearIOputCache(Request $request)
    {
//        $userId = (int)($request->input('user_id'));
//        $poolId = (int)($request->input('pool_id'));
//        app('redis')->del(CacheKey::USER_DATE_PUT_RECORD . ":$userId" . "_" . date("Y-m-d"));
//        app('redis')->del(CacheKey::USER_WEEK_PUT_RECORD . ":$userId" . "_" . date("Y-W"));
//        app('redis')->del(CacheKey::POOL_DATE_PUT_RECORD . ":$poolId" . "_" . date("Y-m-d"));
//        app('redis')->del(CacheKey::POOL_WEEK_PUT_RECORD . ":$poolId" . "_" . date("Y-W"));
//        app('redis')->del(CacheKey::POOL_ROUND . ":$poolId");
//        app('redis')->del(CacheKey::USER_LAST_BIG_DRAW_COUNT);

        /*$keys = app('redis')->keys("pet:*");
        foreach ($keys as $key) {
            app('redis')->del($key);
        }*/
    }

    public function setAuto(Request $request)
    {
        $userId = (int)UID;
        $is_auto  = intval($request->input('is_auto'));
        if (!in_array($is_auto, [1, 0])) {
            throw new BasicException(-1, '非法请求');
        }
        (new DrawManager($this->drawType))->setAuto($userId, $is_auto);
        return Response::sendData([], '成功');
    }
}
